package com.leyou.trade.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.auth.utils.UserContext;
import com.leyou.clients.ItemClient;
import com.leyou.common.exception.LyException;
import com.leyou.item.dto.SkuDTO;
import com.leyou.trade.dto.OrderDTO;
import com.leyou.trade.entity.Order;
import com.leyou.trade.entity.OrderDetail;
import com.leyou.trade.entity.OrderLogistics;
import com.leyou.trade.mapper.OrderMapper;
import com.leyou.trade.service.OrderDetailService;
import com.leyou.trade.service.OrderLogisticsService;
import com.leyou.trade.service.OrderService;
import com.leyou.user.client.UserClient;
import com.leyou.user.dto.AddressDTO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {

    @Autowired
    private ItemClient itemClient;

    @Autowired
    private OrderDetailService orderDetailService;

    @Autowired
    private OrderLogisticsService orderLogisticsService;

    @Autowired
    private UserClient userClient;


    @Override
    @Transactional
    public void createOrder(OrderDTO orderDTO) {
        /**
         * 填充order表
         */
        // 创建order对象
        Order order = new Order();
        // 获取skuid和数量的集合
        Map<Long, Integer> cartsMap = orderDTO.getCarts();
        // 判断是否为空
        if (CollectionUtils.isEmpty(cartsMap)) {
            throw new LyException(400, "下单失败，请求参数错误");
        }
        // 获取所有skuid集合
        List<SkuDTO> skuDTOS = itemClient.querySkuByIds(new ArrayList<>(cartsMap.keySet()));
        // 判断是否为空
        if (CollectionUtils.isEmpty(skuDTOS)) {
            throw new LyException(400, "下单失败");
        }
        // 定义价格变量
        long totalFee = 0;
        // 遍历skuDTOs集合
        for (SkuDTO skuDTO : skuDTOS) {
            // 获取skuId
            Long skuId = skuDTO.getId();
            // 获取价格
            Long price = skuDTO.getPrice();
            // 计算总价
            totalFee += price * cartsMap.get(skuId);
        }
        // 设置总价以及实付款
        order.setTotalFee(totalFee);
        order.setActualFee(totalFee);
        order.setPaymentType(orderDTO.getPaymentType());
        order.setStatus(1);
        order.setUserId(UserContext.getUser().getId());
        order.setPostFee(0L);
        save(order);

        /**
         * orderDetail
         */
        List<OrderDetail> orderDetails = skuDTOS.stream().map(skuDTO -> {
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setOrderId(order.getOrderId());
            orderDetail.setSkuId(skuDTO.getId());
            orderDetail.setNum(cartsMap.get(skuDTO.getId()));
            orderDetail.setTitle(skuDTO.getTitle());
            orderDetail.setSpec(skuDTO.getSpecialSpec());
            orderDetail.setPrice(skuDTO.getPrice());
            orderDetail.setImage(StringUtils.substringBefore(skuDTO.getImages(), ","));
            return orderDetail;
        }).collect(Collectors.toList());
        orderDetailService.saveBatch(orderDetails);

        /**
         * 物流
         */
        AddressDTO addressDTO = userClient.queryAddressById(UserContext.getUser().getId(), orderDTO.getAddressId());

        OrderLogistics orderLogistics = new OrderLogistics();
        orderLogistics.setOrderId(order.getOrderId());
        BeanUtils.copyProperties(addressDTO, orderLogistics);

        orderLogisticsService.save(orderLogistics);

    }
}
